package m.jclecai.com.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Request;
import com.wave.lib.SwipeListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.adapter.BonusOptimizationAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.ShowOrderDialog;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.CalculateBetNums;
import m.jclecai.com.utils.MyLog;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

import static m.jclecai.com.utils.CalculateBetNums.getBonus;

/**
 * Created by ZD on 2017/5/9.
 * 奖金优化
 */

public class BonusOptimizationActivity extends BaseActivity {

    BonusOptimizationAdapter adapter;
    @BindView(R.id.include_multiple_context)
    EditText includeMultipleContext;
    @BindView(R.id.rb_pj)
    RadioButton rbPj;
    @BindView(R.id.rb_br)
    RadioButton rbBr;
    @BindView(R.id.rb_bl)
    RadioButton rbBl;
    @BindView(R.id.rg_tab)
    RadioGroup rgTab;
    @BindView(R.id.lv_body)
    SwipeListView lvBody;
    @BindView(R.id.llContainer)
    LinearLayout llContainer;
    @BindView(R.id.tv_bonus)
    TextView tv_bonus;
    String codes = "";
    //过关玩法
    String num = "";
    //金额/2 注
    String tnum = "1";
    String playtype = "41";
    String type = "0";
    String term = "170510";
    String vote, pass;
    int money = 2;
    int multiple = 1;
    List<JSONObject> result, match;
    private String mPlayTypeNum;
    private String mLotteryMode;


    private ShowOrderDialog mShowOrderDialog;

    @Override
    public int getContentView() {
        return R.layout.activity_bonus_optimization;
    }

    @Override
    public void initData() {
        result = new ArrayList<>();
        match = new ArrayList<>();
        adapter = new BonusOptimizationAdapter(this, result, match, callback);
        lvBody.setAdapter(adapter);
        codes = getIntent().getStringExtra("codes");
        vote = getIntent().getStringExtra("vote");
        pass = getIntent().getStringExtra("pass");
        money = getIntent().getIntExtra("money", 0);
        term=getIntent().getStringExtra(PAY_TERM);
        playtype=getIntent().getStringExtra(PAY_TYPE);
        mPlayTypeNum = getIntent().getStringExtra(PAY_TYPE_NUM);
        String mp = getIntent().getStringExtra(PAY_MULTIPLE);
        Intent intent = getIntent();
        mLotteryMode = getIntent().getStringExtra(PAY_LOTTERY_TYPE);
        multiple = TextUtils.isEmpty(mp) ? 1 : Integer.parseInt(mp);
        tnum = String.valueOf(money / 2);
        optimizType();
        getNum();
        getData();
        changedText();
        includeMultipleContext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence.toString()))
                    return;
                includeMultipleContext.removeTextChangedListener(this);
                int input = Integer.parseInt(charSequence.toString());
                if (input <= 0) {
                    money = 2;
                }else{
                    money = input;
                    if (money % 2 != 0)
                        money = money + 1;
                }
                showET(includeMultipleContext, money);
//                getData();
                includeMultipleContext.addTextChangedListener(this);
                includeMultipleContext.setSelection(
                        charSequence.toString().trim().length());


                return;
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //优化类型
    void optimizType() {
        rgTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_pj:
                        type = "0";
                        break;
                    case R.id.rb_br:
                        type = "1";
                        break;
                    case R.id.rb_bl:
                        type = "2";
                        break;
                }
                getData();
            }
        });
    }

    void getNum() {
        String[] split = pass.split("[,]");
        if (split.length <= 1) {
            num = pass.split("[*]")[0];
            return;
        }
        for (int i = 0; i < split.length; i++) {
            num += split[i].split("[*]")[0];
            if (i < split.length - 1)
                num += ",";
        }
    }


    @OnEditorAction(R.id.include_multiple_context)
    boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            String s = includeMultipleContext.getText().toString();
            if (TextUtils.isEmpty(s) || (!TextUtils.isEmpty(s) && Integer.parseInt(s) <= 0)) {
                MyToast.showToast(BonusOptimizationActivity.this, "计划金额为2的整数倍！");
            }
            showET(includeMultipleContext, money);
            getData();
        }
        return false;
    }

    @OnClick(R.id.include_multiple_cut)
    void cut() {
        money = money - 2;
        if (money / 2 < Integer.parseInt(tnum)) {
            MyToast.showToast(BonusOptimizationActivity.this, "最少" + tnum + "注");
            money = money + 2;
        }
        showET(includeMultipleContext, money);
        getData();
    }

    @OnClick(R.id.include_multiple_add)
    void add() {
        money = money + 2;
        showET(includeMultipleContext, money);
        getData();
    }

//    @OnTextChanged(R.id.include_multiple_context)
//    void textChange(Editable s) {
//        if (TextUtils.isEmpty(s)) return;
//        int input = Integer.parseInt(s.toString());
//        if (input <= 0) {
//            return;
//        }
//        money = input;
//        if (money % 2 != 0)
//            money = money + 1;
//    }


    private String mSlogan;
    private String mWrate;
    private String mSunOrderMode;

    @BindView(R.id.cb_saidan)
    CheckBox mCbBox;

    @Override
    public void initView() {
        leftOptionText("");
        setTitle("奖金优化");

        mShowOrderDialog = new ShowOrderDialog(this, new ShowOrderDialog.OnClickButtonListener() {

            @Override
            public void onClickSure(String mode, String profit, String slogan) {
                //确定;
                mSlogan = slogan;
                mWrate = profit;
                mSunOrderMode = mode;

                payMethod();
            }

            @Override
            public void onClickCancel() {
                //取消；
                mCbBox.setChecked(false);
            }
        },"10","10");
    }

    @OnClick(R.id.tv_pay)
    void pay() {

        //这里要做的一个操作；

        /**
         * 此处提交之前先判断用户是否登录
         */
        if(money <= 0){
            DisPlay("计划金额为2的整数倍！");
            return;
        }

        //这里表示点击的了显示跟单；
        mShowOrderDialog.show(String.valueOf(money)+"",(money*1.0/multiple)+"");


    }

    private void payMethod() {
        String code = formatCodeWithMultiple();
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(getIntent().getStringExtra(PAY_VOTENUMS)));
        intent.putExtra(PAY_MULTIPLE, String.valueOf(multiple));
        intent.putExtra(PAY_MONEY, String.valueOf(money));
        intent.putExtra(PAY_CODES, code);
        intent.putExtra(PAY_TYPE,getIntent().getStringExtra(PAY_TYPE));
        intent.putExtra(PAY_PASS, num);
        intent.putExtra(PAY_TERM, term);
        intent.putExtra(PAY_LOTTERY_TYPE, getIntent().getStringExtra(PAY_LOTTERY_TYPE));

        //这里要添加跟单的操作；
        intent.putExtra(SUN_ORDER_MODE, mSunOrderMode);
        intent.putExtra(SUN_ORDER_SLOGAN, mSlogan);
        intent.putExtra(PAY_WRATE, mWrate);
        intent.putExtra(IS_SHOW_ORDER, "1");

        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    //格式化投注code 如果注数为0过滤掉
    String formatCodeWithMultiple() {
        //这里我们做另外的逻辑；
//        if("混合投注".equals(mLotteryMode)){
            //这里是混合投注的问题；
            return getHunHeFormatCode();
//        }else{
//            return defaultFormatCode();
//        }

    }

    /**
     * 这里是一个默认的格式化code一个方法；
     * @return
     */
    private String defaultFormatCode() {
        String perfix = codes.substring(0,codes.indexOf("|"));
        StringBuilder sb = new StringBuilder();
        multiple = 0;
        for (int i = 0; i < result.size(); i++) {
            multiple += result.get(i).getIntValue("muli");
            sb.append(perfix);
            sb.append("|");
            sb.append(result.get(i).getString("code"));
            sb.append("|");
            sb.append(result.get(i).getString("guoguan").replaceAll("串","*"));
            sb.append("_");
            sb.append(result.get(i).get("muli"));
            if (i < result.size() - 1) {
                sb.append(";");
            }
        }
        if(multiple <= 0)
            multiple = 1;
        adapter.notifyDataSetChanged();
        return sb.toString();
    }

    /**
     * 这里是混合投注的一个格式化的操作
     * @return
     */
    private String getHunHeFormatCode() {
        //这里实现混合投注的格式化操作；
        String perfix = codes.substring(0,codes.indexOf("|"));

        multiple = 1;
        StringBuilder codes=new StringBuilder();
        //这里实现混投的字符串的拼接的实现：
        for (int i = 0; i < result.size(); i++) {
            StringBuilder sb = new StringBuilder();
            sb.append("HH");
            sb.append("|");
            sb.append(result.get(i).getString("code"));
            sb.append("|");
            sb.append(result.get(i).getString("guoguan").replaceAll("串","*"));
            sb.append("|");
            sb.append(result.get(i).get("lotteryid"));
            sb.append("_");
            sb.append(result.get(i).get("muli"));
            if (i < result.size() - 1) {
                sb.append(";");
            }
            codes.append(sb.toString());
        }
        return codes.toString();
    }

    void getData() {
        showDialog();
        HashMap<String, String> pair = new HashMap<>();
        pair.put("codes", codes);
        pair.put("tnum", String.valueOf(money / 2));
        pair.put("num", num);
        pair.put("type", type);
        pair.put("id", "1");
        pair.put("playtype", mPlayTypeNum);
        pair.put("term", term);
        HttpManager.postAsyn(Constant_Url.BONUS_OPTIMIZATION, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyLog.i(e.getMessage());
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                JSONObject jsonObject = FastOk.get(response, JSONObject.class);
                try {//防止数据异常
                    result.clear();
                    match.clear();
                    result.addAll(JSON.parseArray(jsonObject.getString("result"), JSONObject.class));
                    match.addAll(JSON.parseArray(jsonObject.getString("match"), JSONObject.class));
                    changedText();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
            }
        }, pair);
    }

    Callback callback = new Callback(){
        @Override
        public void onClickSetChangedText() {
            super.onClickSetChangedText();
            changedText();
        }

        @Override
        public void delete(int position) {
            super.delete(position);
            result.remove(position);
            lvBody.closeMenuView();
            adapter.notifyDataSetChanged();
            changedText();
        }
    };


    /**
     * 显示控件
     *
     * @param et
     * @param money
     */
    private void showET(EditText et, int money) {
        et.setText(String.valueOf(money));
        if (!TextUtils.isEmpty(et.getText().toString().trim()))
            et.setSelection(et.getText().toString().trim().length());
    }

    void changedText() {
        float[] bonus = new float[result.size() == 0 ? 2 : result.size()];
        int muli = 0;
        float allBonus = 0;
        for (int i = 0; i < result.size(); i++) {
            muli += result.get(i).getIntValue("muli");
            bonus[i] = result.get(i).getFloatValue("tbonus");
            allBonus += result.get(i).getFloatValue("tbonus");
        }
        if (result.size() == 0) {
            List<String> rebuildVote = CalculateBetNums.rebuildVote(vote, pass);
            String sp_max = getBonus(rebuildVote, 1, 1);//最大奖金
            String sp_min = getBonus(rebuildVote, 0, 1);//最小奖金
            bonus[0] = Float.parseFloat(sp_min);
            bonus[1] = Float.parseFloat(sp_max);
        } else {
            bonus[bonus.length - 1] = allBonus;
        }
        Arrays.sort(bonus);
        money = muli * 2;
        showET(includeMultipleContext, money);
        if(money == 0) {
            bonus[0] = 0;
            bonus[bonus.length - 1] = 0;
        }
        tv_bonus.setText(Html.fromHtml(
                String.format(
                        getString(R.string.sc_bonus_optimiiza),
                        money,
                        bonus[0],
                        bonus[bonus.length - 1])
        ));
    }
}
